<template>
  <div class="start">
    <div class="ret">
      <van-nav-bar title="出发点录入" left-text="返回" left-arrow @click-left="toHomeIndex()"/>
    </div>
    <div>
      <van-field
          v-model="fieldValue"
          is-link
          readonly
          label="地区"
          placeholder="请选择所在地区"
          @click="show = true"
      />
      <van-popup v-model="show" round position="bottom">
        <van-cascader
            v-model="cascaderValue"
            title="请选择所在地区"
            :options="options"
            @close="show = false"
            @finish="onFinish"
        />
      </van-popup>
    </div>

    <div>
      <div id="mapContainer"></div>
      <div id="myPageTop">
        <table>
          <tr>
            <td>
              <label>请输入关键字：</label>
            </td>
          </tr>
          <tr>
            <td>
              <input id="tipinput" v-model="keyword" class="input"/>
            </td>
          </tr>
          <tr>
            <td>
              <label>经纬度：</label>
            </td>
          </tr>
          <tr>
            <td>
              <input v-model="keyword1" class="input"/>
              <input type="hidden" id="startLnglat" disabled v-model="startLnglat"/>
              <input id="geo" type="button" class="btn" value="地址 -> 经纬度" @click="hanld">
            </td>
          </tr>
        </table>
      </div>
    </div>

    <div class="dong" @click="toHomeAndCompany">
      <div class="image-home">
        <van-icon name="wap-home-o"/>
      </div>
      <div class="hom"><span>家</span></div>
      <div class="didian">大江苑</div>
    </div>
    <div class="si" @click="toHomeAndCompany">
      <div class="image">
        <van-icon name="cashier-o"/>
      </div>
      <div class="firm"><span>公司</span></div>
      <div class="sdi">设置公司地址</div>
    </div>


    <div class="lishi">
      <van-list>
        <div class="history">
          <van-cell v-for="item in historyList" :key="item.id">
            <div>
              <div class="">{{ item.addressName }}</div>
              <div class="">{{ item.provinceMessage }}</div>
            </div>
          </van-cell>
        </div>
      </van-list>
    </div>

    <van-button type="primary" style="width: 90%;margin-left: 5px;margin-top: 20px;background-color: #4B9EFF"
                @click="toHomeIndex">确认
    </van-button>
  </div>
</template>

<script>
import axios from "axios";
import {useCascaderAreaData} from '@vant/area-data';
import AMapLoader from '@amap/amap-jsapi-loader';

export default {
  data() {
    return {
      form: {
        address: null,
      },
      currentTime: '',
      networkStatus: '',
      batteryLevel: '',
      isCharging: false,
      selectedValue: '',
      cityList: [],
      districtList: [],
      search: "",
      historyList: [],
      historys: {
        addressName: null,
        provinceMessage: null,
      },
      show: false,
      fieldValue: '',
      cascaderValue: '',
      options: useCascaderAreaData(),
      // 搜索框输入内容
      // 搜索结果列表
      map: '',
      keyword: '',
      keyword1: '',
      auto: null,
      placeSearch: null,

      //获取出发点经纬度
      geocoder: null,
      marker: null,
      // 出发点经纬度
      startLnglat: '',
      location: {},
      flag: false
    };
  },
  created() {
    this.findByHistory();
    this.homeAndCompany()
  },
  mounted() {
    this.initMap();

  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy();
    }
  },
  methods: {
    homeAndCompany(){
      this.keyword1 = this.$route.query.startLnglat
      this.keyword = this.$route.query.keyword
    },
    toHomeAndCompany(){
      this.$router.push({
        path: '/homeAndCompany',
      })
    },
    end(){
      this.startaddress = this.$route.query.startaddress
    },
    toHomeIndex() {
      console.log(this.keyword1.lng + ',' + this.keyword1.lat)
      this.$router.push({
        path: '/',
        query: {
          startLatitudeAndLongitude: this.keyword1.lng + ',' + this.keyword1.lat
        }
      })
    },
    hanld() {
      this.flag = true;
      this.initMap()
    },

    initMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "9708bfa416d306b9dbaf55ea4e4a25f2",
      };
      const vm = this;
      AMapLoader.load({
        key: "e6effe38515227141202b9fb6749424e", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.ToolBar", //工具条
          "AMap.Scale", // 比例尺
          "AMap.Geolocation", //定位
          "AMap.PlaceSearch", //查询
          'AMap.AutoComplete',
          "AMap.Marker"
        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
          .then((AMap) => {
            const map = new AMap.Map("mapContainer", {
              // 设置地图容器id
              viewMode: "3D", // 是否为3D地图模式
              zoom: 11, // 初始化地图级别
              resizeEnable: true,
              center: [116.397428, 39.90923], // 初始化地图中心点位置
            });

            //构造地点查询类
            AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete', "AMap.Marker", "AMap.Geocoder"],
                function () {
                  var geocoder = new AMap.Geocoder({
                    city: "010", //城市设为北京，默认：“全国”
                  });
                  //输入提示
                  var autoOptions = {
                    input: "tipinput"
                  };
                  vm.auto = new AMap.AutoComplete(autoOptions);
                  vm.placeSearch = new AMap.PlaceSearch({
                    map: map
                  });
                  // 定位
                  if (vm.flag === false) {
                    var geolocation = new AMap.Geolocation({
                      enableHighAccuracy: true,//是否使用高精度定位，默认:true
                      timeout: 500000,          //超过10秒后停止定位，默认：5s
                      buttonPosition: 'RB',    //定位按钮的停靠位置
                      buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                      zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
                      needAddress: true,      //是否返回地址信息
                      city: '010'
                    });
                    map.addControl(geolocation);
                    geolocation.getCurrentPosition(function (status, result) {
                      if (status === 'complete') {
                        onComplete(result);
                      } else {
                        onError(result)
                      }
                    });
                  }
                  // 转经纬度
                  const marker = new AMap.Marker();
                  const keyword = vm.keyword;//输入的内容
                  geocoder.getLocation(keyword, function (status, result) {
                    if (status === 'complete' && result.geocodes.length) {
                      // onComplete(result)
                      const startLnglat = result.geocodes[0].location;
                      console.log(startLnglat)
                      // 获取经纬度
                      vm.keyword1 = startLnglat;
                      console.log("keyword1:" + startLnglat)
                      document.getElementById('startLnglat').value = startLnglat;
                      marker.setPosition(startLnglat);
                      map.add(marker);
                      map.setFitView(marker);
                    } else {
                      console.log("根据地址查询位置失败")
                    }
                  });
                  //提示查询定位
                  const auto = new AMap.AutoComplete(autoOptions);
                  const placeSearch = new AMap.PlaceSearch({
                    map: map
                  });  //构造地点查询类
                  auto.on("select", select);//注册监听，当选中某条记录时会触发

                  function select(e) {
                    placeSearch.setCity(e.poi.adcode);
                    placeSearch.search(e.poi.name);  //出发地查询
                  }
                });

            function onComplete(data) {
              console.log("定位成功!");
              // findalltext.position=data.position;
              self.position = data.position + "";
              console.log(self.position);
              console.log("定位结果:" + data.position);
              console.log("定位类别:" + data.location_type);
              console.log("精度:" + data.accuracy + "米");
              console.log("是否经过偏移:" + data.isConverted);
              // document.getElementById('status').innerHTML='定位成功'
              var str = [];
              str.push('定位结果：' + data.position);
              str.push('定位类别：' + data.location_type);
              if (data.accuracy) {
                str.push('精度：' + data.accuracy + ' 米');
              }//如为IP精确定位结果则没有精度信息
              str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
              // this.position=str;
              // document.getElementById('result').innerHTML = str.join('<br>');
            }

            //解析定位错误信息
            function onError(data) {
              console.log("定位失败!")
              console.log("失败原因排查信息:" + data.message)
              // 定位失败
              // document.getElementById('status').innerHTML='定位失败'
              // document.getElementById('result').innerHTML = '失败原因排查信息:'+data.;message
            }

          });
    },


    // 全部选项选择完毕后，会触发 finish 事件
    onFinish({selectedOptions}) {
      this.show = false;
      this.fieldValue = selectedOptions.map((option) => option.text).join('/');
      console.log(this.fieldValue)
    },
    findByHistory() {
      axios.post('http://localhost:8081/passenger/history/findHistoryList', this.historys).then(response => {
        console.log(response);
        this.historyList = response.data.data;
      })
    },
  }
}
;
</script>

<style>

.start {
  width: 100%;
  height: 100%;

  #mapContainer {
    width: 100%;
    height: 50vh;
  }

  #myPageTop {
    margin-top: 10px;
    margin-left: 10px;
  }

  .input {
    width: 100%;
    height: 25px;
  }

  .dong {
    width: 35%;
    height: 72px;
    margin-top: 44px;
    line-height: 20px;
    text-align: center;
    margin-left: 20px;
    background: #f6e992;
  }

  .si {
    float: left;
    width: 35%;
    height: 65px;
    margin-top: -61px;
    line-height: 20px;
    text-align: center;
    background-color: #f6e992;
    margin-left: 169px;
  }

  .image-home {
    width: 15px;
    height: 15px;
    margin-left: 10px;
    margin-top: 10px;
  }

  .image {
    width: 15px;
    height: 15px;
    margin-left: 10px;
    margin-top: 10px;
  }

  .firm {
    width: 30px;
    height: 30px;
    line-height: 20px;
    text-align: center;
    margin-left: 39px;
    font-size: 15px;
    margin-top: -16px;
  }

  .hom {
    width: 30px;
    height: 30px;
    line-height: 20px;
    text-align: center;
    margin-left: 39px;
    font-size: 15px;
  }

  .sdi {
    width: 103px;
    height: 30px;
    line-height: 20px;
    text-align: center;
    margin-left: 9px;
    font-size: 11px;
  }

  .didian {
    width: 50px;
    height: 30px;
    line-height: 20px;
    text-align: center;
    margin-left: 30px;
    font-size: 15px;
  }

  .lishi {
    z-index: 999;
    float: left;
    width: 100%;
    height: 100px;
    margin-top: 0px;
    line-height: 50px;
    text-align: center;
    display: inline-block;
  }

  .search {
    width: 100%;
    height: 50px;
    float: left;
  }

}
</style>